import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class select {
    public static void main(String[] args) throws SQLException {
        // 1. 创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("zzl666666");

        // 2. 和数据库服务建立网络连接
        Connection connection = dataSource.getConnection();

        // 3. 构造 SQL
        String sql = "select * from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 4. 执行 SQL , 返回结果是一个对象, 称为 ResultSet
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt("id"); // 列名
            String name = resultSet.getString("name"); // 列名
            System.out.println(id + " " + name);
        }

        // 5. 关闭连接等资源
        resultSet.close();
        preparedStatement.close();
        connection.close();

    }
}
